// pages/order/orderDetail/orderDetail.js
var app =getApp();
var isseue_timer;
var ISSUE_TIME = 300;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    work_order_id: '',//工单ID
    pageIndex:0,//订单状态
    orderDetail:[],
    reasonData: [],
    reasonIndex: "",
    placeholder: '请说明退单原因~',
    reasonShow: true,
    chargebackId: '',//退还订单号
    remarks: '',//退还备注
    tipShow: true,
    dropShow: true,
    finishShow: true,//完成显示
    finishId: '',//完成工单ID
    phone_icon: '../../../images/phone_icon.png',
    stars:5,
    load: true,
    lat1:'',
    lng1:'',
    issue_time: ISSUE_TIME,//下发套餐倒计时5分钟
    issue_falg: false,

    moreOrderShow:false,//订单信息更多
    moreShow: false,//炉具信息 显示更多
    moreShowM1: false,//风机功率 显示更多
    moreShowM2: false,//测量信息 显示更多
    moreProgress: false,//跟多进度

    isOrderSureShow: false,//确认签纸质合同,
    isTransferShow: false,//移交弹窗
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    that.setData({
      work_order_id: options.id
    });

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    that.getOrderDetail();
    that.getReturnReason();


  },
  // 炉具信息 显示更多
  lookMore() {
    this.setData({
      moreShow: !this.data.moreShow
    })
  },
  // 订单信息 显示更多
  lookOrderMore() {
    this.setData({
      moreOrderShow: !this.data.moreOrderShow
    })
  },
  // 风机功率 显示更多
  lookMoreM1() {
    this.setData({
      moreShowM1: !this.data.moreShowM1
    })
  },
  // 测量信息 显示更多
  lookMoreM2() {
    this.setData({
      moreShowM2: !this.data.moreShowM2
    })
  },
  // 进度 查看更多
  lookmoreProgress() {
    this.setData({
      moreProgress: !this.data.moreProgress
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
  // 激活缴费器
  activation: function (e) {
    var that = this;
    var work_order_id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '../activation/activation?work_order_id=' + work_order_id,
    })
  },

  //联系他
  telPhone:function(e){
    var phone = e.currentTarget.dataset.phone;
    wx.makePhoneCall({
      phoneNumber: phone,
    })
  },
  // 跳转紧急联系人
  goEmergency(e) {
    var that = this;
    var user_id = e.currentTarget.dataset.userid;
    var work_order_id = e.currentTarget.dataset.workid;
    var emergency_contact = e.currentTarget.dataset.emergency;

    wx.navigateTo({
      url: '../emergencyContact/emergencyContact?user_id=' + user_id + '&work_order_id=' + work_order_id + '&emergency_contact=' + JSON.stringify(emergency_contact),
    })
  },
  // 订单详情
  getOrderDetail: function(){
    var that = this;
    var id = that.data.work_order_id;
    app.ajax({
      url: 'Engineer/Workorder/workOrderDetail',
      data: { work_order_id: id},
      load: that.data.load,
      msg: '数据加载中...',
      success: function(res){
        that.setData({
          orderDetail:res.data.data,
          pageIndex: res.data.data.work_order_status
        });
        // order_id = res.data.data.order_id;

      }
    })

  },
  // 查看大图
  previewImage(e) {
    var currentImg = e.currentTarget.dataset.url;
    var urls = e.currentTarget.dataset.urls;
    wx.previewImage({
      current: currentImg, // 当前显示图片的http链接
      urls// 需要预览的图片http链接列表
    })
  },
  //获取退单原因列表
  getReturnReason: function () {
    var that = this;
    app.ajax({
      url: 'Common/Common/getReturnReason',
      data: {},
      success: function (res) {
        var data = res.data.data;
        var reasonData = [];
        for (var i in data) {
          reasonData.push({
            id: i,
            content: data[i]
          });

        }
        that.setData({
          reasonData: reasonData,
        })

      }
    })
  },

  //退还订单
  chargeback: function (e) {
    let that = this;
    let reasonShow = false;
    let id = e.currentTarget.dataset.id;
    that.setData({
      reasonShow: reasonShow,
      chargebackId: id
    })
  },
  //退还原因
  bindPickerChange: function (e) {
    let that = this;
    let reasonIndex = e.detail.value;
    that.setData({
      reasonIndex: reasonIndex
    })
  },
  //退换备注
  inputRemarks: function (e) {
    var that = this;
    var remarks = e.detail.value;
    that.setData({
      remarks: remarks
    });
  },
  //确定退还
  confirm: function (e) {
    let that = this;
    let reasonShow = true;
    let tipShow = false;
    var id = that.data.chargebackId;
    var reasonIndex = that.data.reasonIndex;
    var remarks = that.data.remarks;
    var reason_id = reasonIndex == '' ? '' : that.data.reasonData[reasonIndex].id;
    //app.saveFormId(e.detail.formId);
    if (reasonIndex == '' || remarks == '') {
      app.showToast("请填写完整信息", "none", 2000, function () { });
      return;
    }
    app.ajax({
      url: 'Engineer/Workorder/backOrderApply',
      data: {
        work_order_id: id,
        reason_id: reason_id,
        remark: remarks
      },
      success: function (res) {
        if (res.data.code == 1000) {
          app.showToast("退单成功", "none", 2000, function () { });
        } else {
          app.showToast(res.data.message, "none", 2000, function () { });

        }

      }
    })
    that.setData({
      reasonShow: reasonShow,
      tipShow: tipShow,
      remarks: '',
      reasonIndex: ''
    })
    timer = setTimeout(function () {
      let tipShow = true;
      that.setData({
        tipShow: tipShow
      });
      that.getOrderDetail();
    }, 2000);
  },
  //取消退还
  cancel: function () {
    let that = this;
    let reasonShow = true;
    that.setData({
      reasonShow: reasonShow,
      remarks: '',
      reasonIndex: ''
    })
  },
  //确认预约时间
  amendTime: function (e) {
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '../amendTime/amendTime?id=' + id,
    })
  },
  //上门
  dropIn: function (e) {
    let that = this;
    let dropShow = false;
    that.setData({
      dropShow: dropShow,
    })
    // var id = e.currentTarget.dataset.id;
    // var lat1, lng1;
    // wx.getLocation({
    //   type: 'wgs84',
    //   success: function (res) {
    //     lat1 = res.latitude;
    //     lng1 = res.longitude;

    //     that.setData({
    //       dropShow: dropShow,
    //       work_order_id: id,
    //       lat1: lat1,
    //       lng1: lng1
    //     })
    //   }
    // });
  },
  //确定上门
  dropConfirm: function (e) {
    let that = this;
    let dropShow = true;
    var id = that.data.work_order_id;
    var lat1 = that.data.lat1;
    var lng1 = that.data.lng1;
    //app.saveFormId(e.detail.formId);
    app.ajax({
      url: 'Engineer/Workorder/goHome',
      data: {
        work_order_id: id,
        // lat: lat1,
        // lng: lng1
      },
      success: function (res) {
        if (res.data.code == 1000) {
          app.showToast("确认成功", "none", 2000, function () { });
          wx.setStorageSync('tabIndex', 2);
          that.getOrderDetail();
        } else {
          app.showToast(res.data.message, "none", 2000, function () { });
        }
      }
    })

    that.setData({
      dropShow: dropShow
    })
  },
  //取消上门
  dropCancel: function () {
    let that = this;
    let dropShow = true;
    that.setData({
      dropShow: dropShow
    })
  },
  // 确认安装地址
  confirmAddress(e) {
    var that = this;
    var work_order_id = e.currentTarget.dataset.id;
    var type = e.currentTarget.dataset.type;
    if (type != 2) {
      type = 1;
    }
    wx.navigateTo({
      url: '../confirmAddress/confirmAddress?order_id=' + work_order_id + '&type=' + type,
    })
  },
  //导航
  orderMap: function (e) {
    console.log(e)
    var lat = parseFloat(e.currentTarget.dataset.lat)
    var lng = parseFloat(e.currentTarget.dataset.lng)
    wx.openLocation({
      latitude: lat,
      longitude: lng,
      scale: 28
    })
  },
  // 绑定缴费器
  bindEquipment: function (e) {
    var that = this;
    var user_id = e.currentTarget.dataset.user_id;
    wx.navigateTo({
      url: '../../order/import/import?id=' + that.data.work_order_id + "&user_id=" + user_id,
    })
  },
  // 确认完成
  finishOn: function (e) {
    var that = this;
    var finishId = e.currentTarget.dataset.id;
    that.setData({
      finishId: finishId,
    })
    wx.removeStorageSync('basics');//清除缓存
    wx.removeStorageSync('filterelement');//清除缓存
    wx.removeStorageSync('service');//清除缓存
    wx.removeStorageSync('valcontent');//清除缓存
    wx.removeStorageSync('showImg');//清除缓存
    wx.removeStorageSync('upImg');//清除缓存
    wx.removeStorageSync('armature');//清除缓存
    wx.removeStorageSync('need_charge');
    var finishId = e.currentTarget.dataset.id;

    that.setData({
      finishId: finishId,
    })
    // wx.navigateTo({
    //   url: '../newreceipt/newreceipt?id=' + finishId,
    // })
    var bids_arr = e.currentTarget.dataset.bids;
    //判断是否是勘测工单

    if (bids_arr.indexOf('7') == 0) {
      wx.navigateTo({
        url: '../orderSurvey/orderSurvey?id=' + finishId,
      })
    } else {
      wx.navigateTo({
        url: '../newreceipt/newreceipt?id=' + finishId,
      })
    }
  },
  //取消确认完成
  finishCancel: function () {
    var that = this;
    that.setData({
      finishId: '',
      finishShow: true
    })
  },
  //完成订单
  finishConfirm: function (e) {
    var that = this;
    var id = that.data.finishId;
    //app.saveFormId(e.detail.formId);
    app.ajax({
      url: 'Engineer/Workorder/editWorkStatus',
      method: 'POST',
      data: { work_order_id: id },
      success: function (res) {
        if (res.data.code == 1000) {
          app.showToast("工单已完成", "none", 2000, function () { });
          that.setData({
            finishId: '',
            finishShow: true
          })
        } else {
          app.showToast(res.data.message, "none", 2000, function () { });
        }
        _PAGE = 1;
        that.getOrderList();
      }
    })
  },

  //签合同
  sign: function (e) {
    wx.navigateTo({
      url: '../../myCenter/econtract/econtract?contract_id=' + e.currentTarget.dataset.contract_id + "&user_id=" + e.currentTarget.dataset.user_id + "&work_order_id=" + e.currentTarget.dataset.id,
    })
  },
  //企业用户签合同
  signTip() {
    app.showToast("该用户非个人客户,请告知客户登录用户端小程序进行签署!")
  },
  //签纸质合同
  takeOrderReceipt: function (e) {
    var that = this;
    // app.saveFormId(e.detail.formId);
    var contract_id = e.currentTarget.dataset.contract_id;
    var user_id = e.currentTarget.dataset.user_id;
    var work_order_id = e.currentTarget.dataset.id;
    that.setData({
      isOrderSureShow: true,
      contract_id: contract_id,
      user_id: user_id,
      work_order_id: work_order_id,
    })
  },
  // 取消签纸质合同
  orderCancel: function () {
    this.setData({
      isOrderSureShow: false,
    })
  },
  // 确认签纸质合同
  orderSure: function (e) {
    var that = this;
    var Type = that.data.isActive;
    //app.saveFormId(e.detail.formId);
    var URL;
    app.ajax({
      url: 'Engineer/Contract/sign',
      method: "POST",
      data: {
        contract_id: that.data.contract_id,
        contact_type: 3,
        sign_client: 2,
        user_id: that.data.user_id,
        work_order_id: that.data.work_order_id,
      },
      success: function (res) {
        //console.log(res)
        if (res.data.code == 1000) {
          that.setData({
            isshow: true
          })
          app.showToast(res.data.message);
          that.getOrderDetail();
          // wx.navigateBack({
          //   delta:1
          // })
        } else {
          app.showToast(res.data.message);
        }
      }
    })
    that.setData({
      isOrderSureShow: false
    })
  },
  //放大图片
  bigIng: function (e) {
    //var imgs = [];
    //imgs.push(e.currentTarget.dataset.src);
    // wx.previewImage({
    //   urls: imgs,
    // })
    wx.previewImage({
      current: e.currentTarget.dataset.src,
      urls: e.currentTarget.dataset.list,
    })
  },
  //图片加载错误
  orderDetail_error(e) {
    var that = this, orderDetail = that.data.orderDetail;
    orderDetail.product_info.main_pic = '../../../images/none.png'
    that.setData({
      orderDetail: orderDetail
    })
  },
  // 费用详情
  moneyDetail: function(e){
    var that = this;
    var work_order_id = e.currentTarget.dataset.work_order_id;
    console.log(work_order_id);
    wx.navigateTo({
      url: '../moneyDetail/moneyDetail?work_order_id=' + work_order_id,
    })

  },
  //复制缴费器编号
  copyDeviceNo: function (e) {
    console.log(1111);
    var dev = e.currentTarget.dataset.dev;
    console.log(dev);
    wx.setClipboardData({
      data: dev,
      success: function (res) {
        wx.getClipboardData({
          success: function (res) {
            console.log(res.data) // data
          }
        })
      }
    })
  },
  //重新下发套餐
  IssuePackage(e) {
    var that = this;
    var equipment_id = e.currentTarget.dataset.equipment_id;
    var device_no = e.currentTarget.dataset.device_no;
    clearInterval(isseue_timer);
    console.log(that.data.issue_time)
    if (that.data.issue_falg && that.data.issue_time > 0) {
      app.showToast("请不要频繁下发套餐," + ISSUE_TIME / 60 + "分钟后再重新下发");
      return false;
    }
    wx.showModal({
      title: '提示',
      content: '是否需要重新下发套餐？',
      success(res){
        if(res.confirm){
          that.setData({
            issue_falg: true
          })
          that.issue(device_no);
        }
        if(res.cancel){

        }
      },
    })
    // app.showModal("", "是否需要重新下发套餐??", function () {
    //   that.setData({
    //     issue_falg: true
    //   })
    //   that.issue(that.data.orderDetail.contract_id, equipment_id);
    // })
  },
  //下发套餐接口
  issue(device_no) {
    var that = this;
    app.ajax({
      url: "Common/Contract/issuePackage",
      data: { device_no: device_no},
      success: function (res) {
        app.showToast(res.data.message);
        if (res.data.code == 1000) {
          isseue_timer = setInterval(function () {
            var t = that.data.issue_time - 1;
            that.setData({
              issue_time: t
            })
          }, 1000)
        } else {
          that.setData({
            issue_falg: false
          })
        }
      }
    })
  },
  //跳转我的认证
  authentication(e) {
    var that = this;
    var user_id = e.currentTarget.dataset.user_id;
    app.ajax({
      url: "Engineer/Realname/getAuthInfo",
      data: { user_id: user_id },
      success: function (res) {
        if (res.data.code == 1000 && res.data.data.status == -2) {
          wx.navigateTo({
            url: '../../realname/uploadDocuments/uploadDocuments?user_id=' + user_id,
          })
        } else if (res.data.code == 1000 && res.data.data.status == -3) {
          wx.navigateTo({
            url: '../../realname/faceRecognition/faceRecognition?user_id=' + user_id,
          })
        } else if (res.data.code == 1000 && (res.data.data.status == 2 || res.data.data.status == 1)) {
          wx.navigateTo({
            url: '../../realname/myCertification/myCertification?user_id=' + user_id,
          })
        } else {
          wx.navigateTo({
            url: '../../realname/realName/realName?user_id=' + user_id,
          })
        }
      }

    })


  },


  //跳转测试确认单
  orderConfirm(e) {
    var id = e.currentTarget.dataset.id;
    var mytype = e.currentTarget.dataset.type;//数据类型 1试用,2改造
    var code = e.currentTarget.dataset.code;//测试单编码
    var stove_number = e.currentTarget.dataset.stove_number;//改造数量
    wx.navigateTo({
      url: '../orderConfirmOne/orderConfirmOne?work_order_id=' + id + '&type=' + mytype + '&code=' + code + '&stove_number=' + stove_number,
    })
  },

  //移交工单
  orderTransfer(e) {
    var that = this;
    that.setData({
      isTransferShow: true,
    })
  },
  //确认移交
  transferSure() {
    var that = this;
    app.ajax({
      url: 'Engineer/Workorder/workOrderTransfer',
      data: {
        work_order_id: that.data.work_order_id
      },
      success: function (res) {
        if (res.data.code == 1000) {
          that.setData({
            isTransferShow: false,
          })
          app.showToast('移交成功');
          that.getOrderDetail();
        } else {
          app.showToast(res.data.message);
        }
      }
    })
  },
  //取消移交
  cancelTransfer() {
    var that = this;
    that.setData({
      isTransferShow: false,
    })
  },

  //签字
  orderSign(e) {
    var that = this;
    var work_order_id = e.currentTarget.dataset.id;
    var type = 1;//1、测试确认单、2保管清单、3分享确认单
    var work_order_type = e.currentTarget.dataset.type;//1试用2改造
    wx.navigateTo({
      url: '../orderConfirmInfo/orderConfirmInfo?work_order_id=' + work_order_id + '&type=' + type + '&work_order_type=' + work_order_type,
    })
  },

  //拆机确认
  orderDemolition(e) {
    var that = this;
    var work_order_id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '../orderDemolition/orderDemolition?work_order_id=' + work_order_id,
    })
  },

  //查看合同信息
  orderContract(e) {
    var that = this;
    var work_order_id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '../contractList/contractList?work_order_id=' + work_order_id,
    })
  },
  
  //回单
  orderReceipt(e) {
    var that = this;
    var work_order_id = e.currentTarget.dataset.id;
    var is_repair = e.currentTarget.dataset.is_repair;
    wx.navigateTo({
      url: '../orderReceipt/orderReceipt?work_order_id=' + work_order_id + '&is_repair=' + is_repair,
    })
  },
//复制 若有经纬度展示导航功能
setCopy(e){
  var that = this;
  var index = e.currentTarget.dataset.index;
  var lat = that.data.orderData[index].lat;
  var lng = that.data.orderData[index].lng;
  // var lat = 30;
  // var lng = 30;
  if(lat == null && lng == null){
    var address=e.currentTarget.dataset.address;
    wx.setClipboardData({
      data: address,
    })
  }
  else{
    wx.getLocation({
     type: 'gcj02', 
     success: function(res){
      wx.openLocation({
       latitude: lat, // 纬度，范围为-90~90，负数表示南纬
       longitude: lng, // 经度，范围为-180~180，负数表示西经
       scale: 28, // 缩放比例
      })
     }
    })
  }
},
})
